﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class InnomedSearcher : ISiteSearcher
    {
        private const string HOME_URL = "http://www.innomed-respcare.com/";
        private const string PRODUCT_URL = "http://www.innomed-respcare.com/products.htm";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(PRODUCT_URL);
            var gridNode = doc.DocumentNode.SelectSingleNode("//table[@id='AutoNumber1']/tbody");
            var allProds = gridNode.SelectNodes("./tr");

            foreach (HtmlNode node in allProds) {
                Product p = GetProductByNode(node);
                if (p != null) {
                    result.Add(p);
                }
                if (result.Count >= criteria.NumOfProduct) {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode trNode) {
           if(trNode.ChildNodes.Count < 5)
           {
               return null;
           }
            var img = trNode.SelectSingleNode("./td[3]/a/img");
            Product p = new Product();
            if(img != null)
            {
                var imgSrc = img.GetAttributeValue("src", HOME_URL);
                imgSrc = imgSrc == HOME_URL ? HOME_URL : HOME_URL + imgSrc;
                p.ThumbImg = imgSrc;
            }
            var prodName = trNode.SelectSingleNode("./td[4]/font/a");
            return p;
        }
        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
